import os
from typing import Any

from dotenv import load_dotenv


def getConfigData(key: str = "") -> Any:
    load_dotenv()
    return os.getenv(
        key)


def get_boolean_fun(key) -> bool:
    value: str = getConfigData(key)
    return value.lower() == "true" if value is not None else False


class Config:
    def __init__(self):
        self.WTF_CSRF_ENABLED = False
        self.SQLALCHEMY_DATABASE_URI = getConfigData("SQLALCHEMY_DATABASE_URI")
        self.SQLALCHEMY_ENGINE_OPTIONS = {
            "pool_size": getConfigData("SQLALCHEMY_POOL_SIZE"),
            "pool_recycle": getConfigData("SQLALCHEMY_POOL_RECYCLE"),
            "max_overflow": getConfigData("MAX_OVERFLOW"),
            "pool_use_lifo":getConfigData("POOL_USE_LIFO"),
            "connect_args": {
                "connect_timeout": 10  # 连接超时10秒
            }
        }
        self.SQLALCHEMY_ECHO = get_boolean_fun("SQLALCHEMY_ECHO")
        self.REDIS_HOST = getConfigData("REDIS_HOST")
        self.REDIS_PORT = getConfigData("REDIS_PORT")
        self.REDIS_USRNAME = getConfigData("REDIS_USRNAME")
        self.REDIS_PASSWORD = getConfigData("REDIS_PASSWORD")
        self.REDIS_DB = getConfigData("REDIS_DB")
        self.REDIS_USE_SSL = get_boolean_fun("REDIS_USE_SSL")
        self.CELERY = {
            "worker_max_tasks_per_child": 1,
            "broker_url": f"redis://{self.REDIS_USRNAME}:{self.REDIS_PASSWORD}@{self.REDIS_HOST}:{self.REDIS_PORT}/{int(getConfigData('CELERY_BROKER_DB'))}",
            "result_backend": f"redis://{self.REDIS_USRNAME}:{self.REDIS_PASSWORD}@{self.REDIS_HOST}:{self.REDIS_PORT}/{int(getConfigData('CELERY_RESULT_BACKEND_DB'))}",
            "task_ignore_result": get_boolean_fun("CELERY_TASK_IGNORE_RESULT"),
            "result_expires": int(getConfigData("CELERY_RESULT_EXPIRES")),
            "broker_connection_retry_on_startup": get_boolean_fun("CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP"),
        }

